<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.skuPrefix" placeholder="货号" clearable style="width: 130px; margin-top: 8px;" class="filter-item" />
      <el-button v-waves class="filter-item" style="margin-left: 10px; margin-top: 8px;" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <router-link :to="{name:'DistributorOrder',params:{status:1}}" style="margin-left: 10px;">
        <el-button type="info" icon="el-icon-right">
          前往付款
        </el-button>
      </router-link>
    </div>

    <div v-if="description">
      <span>{{ description }}</span>
    </div>
    <br />

    <div v-if="list && list.length > 0">
      <el-table v-loading="listLoading" :data="list" :header-cell-style="headerCellStyle" border stripe element-loading-text="拼命加载中">
        <el-table-column prop="inventoryList" type="expand">
          <template slot-scope="scope">
            <el-table :data="scope.row.supplierInventoryList" border stripe style="width: 100%">
              <el-table-column label="货源名称" prop="supplierChannelName" align="center" />
              <el-table-column label="货号" prop="sku" align="center" />
              <el-table-column v-for="col in scope.row.extendColList" :key="col" :label="col" align="center">
                <template slot-scope="{row}">
                  <el-link type="primary" @click="handleBooking(scope.row, row, col)">{{ row.extendValues | extendValuesFilter(col) }}</el-link>
                </template>
              </el-table-column>
              <el-table-column label="合计" prop="total" align="center" width="110px" />
              <el-table-column label="折扣价" align="center" width="70px">
                <template slot-scope="{row}">
                  <div style="text-decoration: line-through;">{{ row.marketPrice }}</div>
                  <div style="color: #FF0000;">{{ row.discountPrice }}</div>
                </template>
              </el-table-column>
              <el-table-column label="折扣" prop="discount" align="center" width="60px" />
              <el-table-column label="库存更新时间" prop="createTime" align="center" width="160px" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="货号" align="center" min-width="110px">
          <template slot-scope="{row}">
            <span style="float: left;">{{ row.sku }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌" align="center" min-width="110px">
          <template slot-scope="{row}">
            <span style="float: left;">{{ row.brandName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center" min-width="110px">
          <template slot-scope="{row}">
            <span style="float: left;">{{ row.productName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="系列" align="center" min-width="110px">
          <template slot-scope="{row}">
            <span style="float: left;">{{ row.productSeries }}</span>
          </template>
        </el-table-column>
        <el-table-column label="大类" align="center" width="50px">
          <template slot-scope="{row}">
            <span>{{ row.goodsCategoryName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年份" align="center" width="60px">
          <template slot-scope="{row}">
            <span>{{ row.year }}</span>
          </template>
        </el-table-column>
        <el-table-column label="季节" align="center" width="50px">
          <template slot-scope="{row}">
            <span>{{ row.season }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" width="50px">
          <template slot-scope="{row}">
            <span>{{ row.goodsSexName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="颜色" align="center" min-width="110px">
          <template slot-scope="{row}">
            <span style="float: left;">{{ row.color }}</span>
          </template>
        </el-table-column>
        <el-table-column label="吊牌价" align="center" width="70px">
          <template slot-scope="{row}">
            <span style="float: right;">{{ row.marketPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="卖点" align="center" min-width="110px">
          <template slot-scope="{row}">
            <span style="float: left;">{{ row.saleProps }}</span>
          </template>
        </el-table-column>
        <el-table-column label="材质" align="center" min-width="110px">
          <template slot-scope="{row}">
            <span style="float: left;">{{ row.material }}</span>
          </template>
        </el-table-column>
        <el-table-column label="细节备注" align="center" min-width="110px">
          <template slot-scope="{row}">
            <span style="float: left;">{{ row.remark }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="在线下单" :visible.sync="bookingVisible" width="80%">
      <el-form ref="bookingForm" :model="booking" label-width="100px" style="margin-left:0px;">
        <span style="text-align: center; display: block;">地址格式为：张三 ，13888888888 ，0518-88888888，江苏省 连云港市 新浦区 朝阳中路77号二楼 ，222000</span>
        <el-form-item label="拆分">
          <el-input v-model="splitBookingInfo" type="textarea" :rows="2" placeholder="请输入地址信息" @blur="onSplitBookingInfoBlur" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="booking.name" placeholder="请输入姓名" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="手机" prop="mobilephone">
          <el-input v-model="booking.mobilephone" placeholder="请输入手机" style="width: 200px;" maxlength="11" show-word-limit />
        </el-form-item>
        <el-form-item label="座机" prop="telephone">
          <el-input v-model="booking.telephone" placeholder="请输入座机" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select v-model="booking.province" placeholder="省份" clearable filterable style="width: 200px;">
            <el-option v-for="item in provinceOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input v-model="booking.city" placeholder="市" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="区" prop="district">
          <el-input v-model="booking.district" placeholder="区" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="邮编" prop="zipcode">
          <el-input v-model="booking.zipcode" placeholder="请输入邮编" style="width: 200px;" maxlength="6" show-word-limit />
        </el-form-item>
        <el-form-item label="自定义订单号" prop="orderId">
          <el-input v-model="booking.orderId" placeholder="请输入自定义订单号" style="width: 200px;" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="booking.address" type="textarea" :rows="2" placeholder="请输入地址信息" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="booking.remark" type="textarea" :rows="2" maxlength="200" show-word-limit />
        </el-form-item>
        <el-table :data="bookingProductList">
          <el-table-column label="商品明细" align="left" width="160px">
            <template slot-scope="{row}">
              <div>货号:{{ row.sku }}</div>
              <div>货源:{{ row.supplierChannelName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="" align="left" width="160px">
            <template slot-scope="{row}">
              <div>品牌:{{ row.brandName }}</div>
              <div>系列:{{ row.productSeries }}</div>
            </template>
          </el-table-column>
          <el-table-column label="" align="left" width="110px">
            <template slot-scope="{row}">
              <div>类别:{{ row.goodsCategoryName }}</div>
              <div>季节:{{ row.year+row.season }}</div>
            </template>
          </el-table-column>
          <el-table-column label="尺码" align="center" width="60px">
            <template slot-scope="{row}">
              <span>{{ row.size }}</span>
            </template>
          </el-table-column>
          <el-table-column label="零售价" align="center" min-width="110px">
            <template slot-scope="{row}">
              <span>{{ row.marketPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="折扣" align="center" min-width="110px">
            <template slot-scope="{row}">
              <span>{{ row.discount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="折扣价" align="center" min-width="110px">
            <template slot-scope="{row}">
              <span>{{ row.discountPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存" align="center" width="80px">
            <template slot-scope="{row}">
              <span>{{ row.total }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" width="160px">
            <template slot-scope="{row}">
              <el-input-number v-model="row.qty" size="mini" :min="0" :max="row.total" @change="handleBookingProductQtyChange(row)" />
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center" min-width="110px">
            <template slot-scope="{row}">
              <span>{{ row.cost }}</span>
            </template>
          </el-table-column>
          <el-table-column label="快递/邮费" align="center" min-width="110px" />
          <el-table-column label="重量" align="center" width="60px">
            <template slot-scope="{row}">
              <span>{{ row.weight }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bookingClear">清空</el-button>
        <el-button type="danger" @click="bookingVisible = false">继续选货</el-button>
        <el-button type="primary" @click="bookingConfirm">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { Message } from 'element-ui'
import { fetchEnum } from '@/api/system-api'
import { getProductInventory, booking } from '@/api/distributor/distribution-api'
import waves from '@/directive/waves'
import { toOptionsList } from '@/utils/index'

export default {
  name: 'DistributorBooking',
  directives: { waves },
  filters: {
    extendValuesFilter(extendValues, col) {
      if (extendValues) {
        const value = extendValues[col]
        if (value) {
          return value
        }
      }
      return '-'
    }
  },
  data() {
    return {
      descriptionTemplate: '共找到了 {0} 件商品',
      listQuery: {
        skuPrefix: null
      },

      listLoading: false,
      description: null,
      list: null,

      provinceOptions: [],
      bookingVisible: false,
      splitBookingInfo: null,
      booking: {
        name: null,
        mobilephone: null,
        telephone: null,
        province: null,
        city: null,
        district: null,
        zipcode: null,
        orderId: null,
        address: null,
        remark: null
      },
      bookingProductList: null

    }
  },
  async created() {
    await this.initLoad()
  },
  methods: {
    async initLoad() {
      const enumCodes = ['PROVINCE']
      const { data } = await fetchEnum(enumCodes)
      for (const e of data) {
        if (e.code === 'PROVINCE') {
          if (e.options) {
            this.provinceOptions = toOptionsList(e.options, 'code', 'name')
          }
        }
      }
      this.initListQuery()
    },
    getList() {
      if (this.listQuery && this.listQuery.skuPrefix && this.listQuery.skuPrefix.length >= 4) {
        this.listLoading = true
        getProductInventory(this.listQuery).then(response => {
          const { data } = response
          this.description = this.descriptionTemplate.format(data.count)
          this.list = data.list
          setTimeout(() => {
            this.listLoading = false
          }, 1 * 1000)
        }).catch(error => {
          Message({
            message: error,
            type: 'error',
            duration: 5 * 1000
          })
          this.listLoading = false
        })
      } else {
        Message({
          message: '为保证查询速度，请输入至少输入4位字符',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    initListQuery() {
      this.listQuery = {
        skuPrefix: null
      }
    },

    handleFilter() {
      this.getList()
    },
    headerCellStyle({ row, rowIndex }) {
      return 'background-color: #42b983; color: #FFF;'
    },
    handleBooking(product, supplierInventory, col) {
      this.splitBookingInfo = null
      this.booking = {
        name: null,
        mobilephone: null,
        telephone: null,
        province: null,
        city: null,
        district: null,
        zipcode: null,
        orderId: null,
        address: null,
        remark: null
      }
      var bookingProductList = []
      var bookingProduct = {
        sku: product.sku,
        brandId: product.brandId,
        brandName: product.brandName,
        supplierChannelId: supplierInventory.supplierChannelId,
        supplierChannelName: supplierInventory.supplierChannelName,
        productSeries: product.productSeries,
        goodsCategory: product.goodsCategory,
        goodsCategoryName: product.goodsCategoryName,
        year: product.year,
        season: product.season,
        size: col,
        marketPrice: supplierInventory.marketPrice,
        discount: supplierInventory.discount,
        discountPrice: supplierInventory.discountPrice,
        total: supplierInventory.total,
        qty: 0,
        cost: 0.00,
        weight: product.weight
      }
      bookingProductList.push(bookingProduct)
      this.bookingProductList = bookingProductList
      this.bookingVisible = true
    },

    onSplitBookingInfoBlur() {
      if (this.splitBookingInfo) {
        const array = this.splitBookingInfo.split(/[,，]/)
        if (array[0]) {
          this.booking.name = array[0].trim()
        }
        if (array[1]) {
          this.booking.mobilephone = array[1].trim()
        }
        if (array[2]) {
          this.booking.telephone = array[2].trim()
        }
        if (array[3]) {
          const addressArray = array[3].split(/[ ]/)
          if (addressArray[0]) {
            this.booking.province = addressArray[0].trim()
          }
          if (addressArray[1]) {
            this.booking.city = addressArray[1].trim()
          }
          if (addressArray[2]) {
            this.booking.district = addressArray[2].trim()
          }
          if (addressArray[3]) {
            this.booking.address = addressArray[3].trim()
          }
        }
        if (array[4]) {
          this.booking.zipcode = array[4].trim()
        }
      }
    },
    handleBookingProductQtyChange(row) {
      row.cost = row.discountPrice * row.qty
    },
    bookingClear() {
      this.splitBookingInfo = null
      this.booking = {
        name: null,
        mobilephone: null,
        telephone: null,
        province: null,
        city: null,
        district: null,
        zipcode: null,
        orderId: null,
        address: null,
        remark: null
      }
    },
    bookingConfirm() {
      var bookingParam = {
        name: this.booking.name,
        mobilephone: this.booking.mobilephone,
        telephone: this.booking.telephone,
        province: this.booking.province,
        city: this.booking.city,
        district: this.booking.district,
        zipcode: this.booking.zipcode,
        customizedOrderId: this.booking.orderId,
        address: this.booking.address,
        remark: this.booking.remark,
        details: []
      }
      for (const bookingProduct of this.bookingProductList) {
        if (bookingProduct.qty >= 1) {
          const detail = {
            sku: bookingProduct.sku,
            supplierChannelId: bookingProduct.supplierChannelId,
            normalizedSize: bookingProduct.size,
            qty: bookingProduct.qty,
            marketPrice: bookingProduct.marketPrice,
            discountPrice: bookingProduct.discountPrice,
            deliveryChargePreEach: 0,
            pricePreEach: bookingProduct.discountPrice,
            priceTotal: bookingProduct.cost,
            supplierChannelDeliveryChargeId: null
          }
          bookingParam.details.push(detail)
        }
      }
      booking(bookingParam).then(response => {
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 1 * 1000
        })
        this.bookingVisible = false
      }).catch(error => {
        Message({
          message: error,
          type: 'error',
          duration: 5 * 1000
        })
      })
    }

  }
}

</script>
